package com.junglone.gateway.predicate;

import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

/**
 * Description: 自定义的断言工厂
 *
 * @author junglone: <a href="mailto:cjlnzb@hotmail.com">cjlnzb@hotmail.com</a>
 * @since 2020/09/24 15:15
 */
@Component
public class MyCustomRoutePredicateFactory extends AbstractRoutePredicateFactory<MyCustomRoutePredicateFactory.Config> {


    private static final Logger LOGGER = LoggerFactory.getLogger(MyCustomRoutePredicateFactory.class);

    /**
     * METHOD key.
     */
    public static final String METHOD = "method";

    public MyCustomRoutePredicateFactory() {

        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList(METHOD);
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {

        // grab configuration from Config object
        return exchange -> {
            // grab the request
            ServerHttpRequest request = exchange.getRequest();
            // take information from the request to see if it
            // matches configuration.
            return matches(config, request);
        };
    }

    /**
     * Description: 业务处理
     *
     * @param config
     * @param request
     *
     * @return 处理结果
     *
     * @author junglone: <a href="mailto:cjlnzb@hotmail.com">cjlnzb@hotmail.com</a>
     * @since 2020/09/24 16:14
     */
    private boolean matches(Config config, ServerHttpRequest request) {

        String strMethod = request.getMethod().name();

        LOGGER.info("request.method == {} ========= config.method == {}, path ==== {}",
                strMethod, config.getMethod(), request.getPath());

        // 只允许指定的请求方式
        return strMethod.equalsIgnoreCase(config.getMethod());
    }

    /**
     * Description:
     *
     * @author junglone: <a href="mailto:cjlnzb@hotmail.com">cjlnzb@hotmail.com</a>
     * @since 2020/09/24 15:15
     */
    public static class Config {

        private String method;

        public String getMethod() {

            return method;
        }

        public void setMethod(String method) {

            this.method = method;
        }

    }
}
